/**
 * Created by Administrator on 2018-10-16.
 */
//设置应用名称
var webContext =  localStorage.XD$ADMIN$pathname || "xdSysAdmin";
//设置系统管理Sys文件路径
var adminPath = "reportAdmin"
//访问应用基础路径
var basePath =  window.location.protocol+"//"+window.location.host+"/" + webContext;
var headTitle = localStorage.getItem("headTitle")
var sysName = localStorage.getItem("sysName")
var sysLogo = localStorage.getItem("sysLogo")
var copyRight = localStorage.getItem("copyRight")
var userNo = localStorage.getItem("userNo")
var webIcon = localStorage.getItem("webIcon")

///////////////////////2.加载css、公共js///////////////////////////////////
document.writeln('<meta charset="UTF-8">');
document.writeln("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
document.writeln('<title>'+ headTitle+'</title>');
document.writeln('<meta name="renderer" content="webkit|ie-comp|ie-stand">');
document.writeln('<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">');
document.writeln('<meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />');
document.writeln("<meta http-equiv=\"Expires\" content=\"0\">");
document.writeln("<meta http-equiv=\"Pragma\" content=\"no-cache\">");
document.writeln("<meta http-equiv=\"Cache-control\" content=\"no-cache\">");
document.writeln("<meta http-equiv=\"Cache\" content=\"no-cache\">");




if(webIcon !=null && webIcon != "" && webIcon != "null"){
    document.writeln('<link id="webIcon" rel="shortcut icon" href="'+basePath+'/static/images/favicon.ico" type="image/x-icon" />')
}

document.writeln('<link rel="stylesheet" href="'+basePath+'/'+adminPath+'/css/font.css">');

document.writeln('<link rel="stylesheet" href="'+basePath+'/layui/css/layui.css">');
//document.writeln('<link rel="stylesheet" href="'+basePath+'/'+adminPath+'/css/admin.css">');
document.writeln('<link rel="stylesheet" href="'+basePath+'/'+adminPath+'/css/xd.css">');
//layui第三方插件：select 多选
document.writeln('<link rel="stylesheet" href="'+basePath+'/layui/css/formSelects-v4.css">');


document.writeln('<script src="'+basePath+'/layui/layui.js" charset="utf-8"></script>');

document.writeln('<script type="text/javascript" src="'+basePath+'/static/js/jquery.min.1.11.3.js"></script>');
document.writeln('<script type="text/javascript" src="'+basePath+'/static/js/jquery.cookie.js"></script>');

document.writeln('<!--[if lt IE 9]>');
document.writeln('<script type="text/javascript" src="'+basePath+'/static/js/html5.min.js"></script>');
document.writeln('<script type="text/javascript" src="'+basePath+'/static/js/respond.min.js"></script>');
document.writeln('<![endif]-->');
//导出页面JSON到Excel
document.writeln('<script src="'+basePath+'/static/js/jsonExportExcel.js" charset="utf-8"></script>');
document.writeln('<script src="'+basePath+'/static/js/dateUtil.js" charset="utf-8"></script>');
document.writeln('<script src="'+basePath+'/jsPlugin/clipboard.min.js" charset="utf-8"></script>');
document.writeln('<script src="'+basePath+'/jsPlugin/tableMerge.js" charset="utf-8"></script>');
document.writeln('<script src="'+basePath+'/echartsResource/echarts.min.js" charset="utf-8"></script>');

var token =  localStorage.getItem("token") || $.cookie("token")
var urlParam=window.location.search;

/****
 * 设置dataTable工具栏,此处只能同步加载，异步toolbar加载不出来
 * ***/

var commonUtil = {
    toolbarHTML:function(){//获取菜单按钮
        var html = true
        $.ajax(basePath+"/function/getFuncOptsByAuth"+urlParam,{
            dataType:'json',
            async: false,
            success:function(rst){
                if(rst.code==0){
                    html = rst.data
                }else{
                    layer.msg(rst.msg)
                    html =  true
                }
            }
        })
        return html
    },
    getFormValue:function(element){//获取表单数据：针对select做特殊处理
        var domId = element || "form";
        var param = {token:token}
        var formArray = $(domId).serializeArray();
        var selectArray = []
        $(domId).find("select").each(function(index,element){//select 特殊处理：使用 'value1','value2' 形式
            //console.log($(element).attr("_name"),typeof $(element).attr("_name"))
            if(!$.contains(selectArray,$(element).attr("_name"))){
                selectArray.push($(element).attr("_name"))
            }else  if(!$.contains(selectArray,$(element).attr("name"))){
                selectArray.push($(element).attr("name"))
            }
        })

        $.each(formArray,function(index,item){
            var value = item.value
            for(var i =0;i< selectArray.length;i++){
                if(selectArray[i] == item.name ){
                    value =   item.value.split(',');
                    value = "'"+ value.join("','")+"'"
                    break;
                }
            }
            param[item.name] =  value
        })
        return param
    },
    /**将数组转换成：'aa','aa','dd' 格式
     *  field:数组元素值字段
    **/
    arrayFormat2Str:function(array,field){
        var result = ""
        var type = ( typeof array )
        if(type == "object"){
            var selectArray = []
            $.each(array,function(index,element){//select 特殊处理：使用 'value1','value2' 形式
                //console.log($(element).attr("_name"),typeof $(element).attr("_name"))
                if(!$.contains(selectArray,$(element).attr(field))){
                    selectArray.push($(element).attr(field))
                }
            })

            if(selectArray.length >= 1){
                result = "'"+ selectArray.join("','")+"'"
            }

        }else{
            result = array
        }
        return result
    },

    getFormValueNormal:function(element){//获取表单数据
        var domId = element || "form";
        var param = {}
        var formArray = $(domId).serializeArray();
        $.each(formArray,function(index,item){
            param[item.name] =   item.value
        })
        return param
    },
    downLoad:function(exportData,title,exportHead){//下载数据
        JSONToExcelConvertor(exportData, title, exportHead)
    },
    renderTableOPT:function(table,tabOption){//获取菜单按钮
        var obj
        $.ajax(basePath+"/function/getFuncOptsByAuthList"+urlParam,{
            //data:{token:localStorage.getItem("token")},
            dataType:'json',
            //async: false,
            success:function(rst){
                var toolbar = ""
                if(rst.code==0 && rst.data != null && rst.data != "" ){
                    $(rst.data).each(function(index,item){
                        toolbar +=
                            "<button class='layui-btn "+item.STYLE+"' lay-event='"+item.OPERATE_NO+"'  _type='"+item.TYPE+"' _action='"+item.ACTION+"' ><i class='layui-icon "+item.ICON+"'></i>"+item.OPERATE_NAME+"</button>"
                    })
                    tabOption.toolbar = "<div><div class='layui-btn-group'>"+ toolbar+"</div></div>";
                }else{
                    tabOption.toolbar = false
                }
                //console.log( tabOption.toolbar)
                obj = table.render(tabOption)
            }
        })
        return obj
    },
    copyToClipBoard:function(dom,content){//复制内容到剪切板
        var flag = true
        var clipboard = new ClipboardJS(dom, {
            text: function() {
                return content;
            }
        });
        clipboard.on('success', function(e) {
            clipboard.destroy();
            return true
        });

        clipboard.on('error', function(e) {
            alert("复制失败")
            clipboard.destroy();
            return false
        });
    },
    nvl:function(val1,val2){//盘空取值
        if( $.isEmptyObject(val1)  ){
            return val2
        }
        return val1
    },
    openPage:function(title,url,w,h,scrollbar){//打开一个页面弹窗
        var maxmin = true
        if (title == null || title == '') {
            title = false;
            maxmin = false
        }else{
            title = "<i class='layui-icon layui-icon-note'></i>&nbsp;"+title
        };
        if (url == null || url == '') {
            url="404.html";
        };
        if (w == null || w == '') {
            w= '95%';
        };
        if (h == null || h == '') {
            h= '95%';
        };
        layer.open({
            type: 2,
            area: [w , h  ],
            fix: false, //不固定
            maxmin: maxmin,
            shadeClose: true,
            shade:0.4,
            offset: '1%',
            scrollbar:scrollbar|| true,
            title:  title,
            content: url
        });
    },
    parseNumber:function(d){
        return Number(d)
    },

    mergeCell:function (id,mergeField){//合并单元格
        /**
         *合并列单元格
         * mergeField:数组：[{refColumn1:targetColumn2},{refColumn1:targetColumn2},]
         * dom : table:id
         * @type {string}
         */
        var tableSelector = "div[lay-id="+id + "] .layui-table-body .layui-table"
        var trdom = $(tableSelector).find("tr[data-index='0']")
        $.each(mergeField, function (index,map) {
            $.each(map,function(key,value){
                var _w_table_colnum = trdom.find("td[data-field="+commonUtil.nvl(key,"-1-")+"]")
                _w_table_colnum = _w_table_colnum.length >  0 ? _w_table_colnum[0].cellIndex + 1 : -1

                var _w_table_ref_colnum  = trdom.find("td[data-field='"+commonUtil.nvl(value,"-1-")+"']")
                _w_table_ref_colnum = _w_table_ref_colnum.length >  0 ? _w_table_ref_colnum[0].cellIndex + 1 : -1

                _w_table_rowspan_ref(tableSelector,_w_table_ref_colnum ,_w_table_colnum)
            })
        })
    },
    downLoadExcel:function(form,panelId){
        /**
         * //下载Excel：form表单，panelId
         * ajax:返回参数：code:0,msg:正常, 其他错误
         * form 主要获取参数
         * panelId:获取下载数据信息
         */
        var loadIndex =  layer.load()
        var url = basePath+"/xdWidgetPanel/dowLoad?panelId="+panelId ;
        $("form").attr("action",url).attr("method","post")
            .append($(form).html())
            .append('<input type="hidden" lay-submit lay-filter="downLoad" >').submit(function(obj){
            //console.log(obj);
        }).remove()
    },
    setDefaultDate:function(flag){//设置日期控件默认值
        var now = new Date()
        switch (flag){
            case "weekFirst":
                now = dateUtil.getFirstDayOfWeek(now)
                break;
            case "monthFirst":
                now = dateUtil.getFirstDayOfMonth(now)
                break;
            case "now7day":
                now = dateUtil.getLastNDay(7)
                break;
            case "now30day":
                now = dateUtil.getLastNDay(30)
                break;
            default :
                now = new Date().getTime();
        }
        return now
    },
    parseServerHtml:function(returnstr){//主要用于解析后台回传到页面后特殊字符被转意的情况
        var reg1 = new RegExp("&quot;","g");
        var reg2 = new RegExp("&lt;","g");//<
        var reg3 = new RegExp("&gt;","g");//>
        return returnstr.replace(reg1,"\"").replace(reg2,"\<").replace(reg3,"\>")
    },
    closeLayerFrame: function () {//关闭layer的frame弹窗
        var index =  parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    }

}


